﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Xss.Xml
{
    public class XmlAttribute
    {
        /// <summary>
        /// 获取指定元素的属性值
        /// </summary>
        /// <param name="xe">指定元素</param>
        /// <param name="name">属性名称</param>
        /// <returns></returns>
        public static string Value(XElement xe, string name)
        {
            return Value(xe, name, string.Empty);
        }

        /// <summary>
        /// 获取指定元素的属性值
        /// </summary>
        /// <param name="xe">指定元素</param>
        /// <param name="name">属性名称</param>
        /// <param name="value">默认值</param>
        /// <returns></returns>
        public static string Value(XElement xe, string name, string value)
        {
            var attr = xe.Attribute(name);
            return attr == null ? value : attr.Value;
        }

        public static T Value<T>(XElement xe, string name, Func<string, T> fn, T value)
        {
            var attr = Value(xe, name, string.Empty);
            return
                string.IsNullOrEmpty(attr)
                ? value
                : fn(attr);
        }
    }
}
